package com.wzh.mysending.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wzh.mysending.StrongService;
import com.wzh.mysending.utils.ServiceUtil;


/**
 * Created by Hu on 2017/3/22.
 */

public class KeepService extends Service {
    private static final String TAG = "KeepService===";
    private String Process_Name = "com.wzh.mysending.service:main";

    /**
     *启动Service1
     */
    private StrongService startS1 = new StrongService.Stub() {

        @Override
        public void stopService() throws RemoteException {
            Intent i = new Intent(getBaseContext(), MainService.class);
            getBaseContext().stopService(i);
        }

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void startService() throws RemoteException {
            Intent i = new Intent(getBaseContext(), MainService.class);
            getBaseContext().startService(i);

        }
    };
    @Override
    public void onTrimMemory(int level){
//        Toast.makeText(getBaseContext(), "Service2 onTrimMemory..."+level, Toast.LENGTH_SHORT)
//                .show();
        startMainService();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"onCreate");
        startMainService();
    }

    /**
     * 判断Service1是否还在运行，如果不是则启动Service1
     */
    private  void startMainService(){
        boolean isRun = ServiceUtil.isProessRunning(this, Process_Name);
        if (isRun == false) {
            try {
//                Toast.makeText(getBaseContext(), "重新启动 Service1", Toast.LENGTH_SHORT).show();
                startS1.startService();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"onStartCommand");
        return START_STICKY;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return (IBinder) startS1;
    }
}
